<template>
  <el-card
    class="form-container"
    shadow="never"
  >
    <el-form
      :model="content"
      ref="contentFrom"
      label-width="150px"
    >
      <el-form-item
        label="服务名称："
        prop="specName"
        :rules="[
          { required: true, message: '服务名称不能为空', trigger: 'change'}
        ]"
      >
        <el-input
          v-model="content.specName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="分类"
        prop="serType"
        :rules="[
          { type: 'array', required: true, message: '分类不能为空', trigger: 'change'}
        ]"
      >
        <el-cascader
          v-model="content.serType"
          :options="serTypeList"
          class="input-width"
          @change="serTypeChange()"
        ></el-cascader>
      </el-form-item>

      <el-form-item
        label="品类："
        prop="packageName"
        :rules="[
          { required: true, message: '请选择品类', trigger: 'change' }
        ]"
      >
        <el-autocomplete
          v-model="content.packageName"
          :fetch-suggestions="packageQuerySearchAsync"
          placeholder="请输入内容"
          @select="packageSelect"
          class="input-width"
        ></el-autocomplete>
        <el-button @click="priceChange"> 价格配置</el-button>
      </el-form-item>
      <el-form-item v-show="showPrice">
        <el-table
          :data="skuTableData"
          ref="multipleTable"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <el-table-column
            v-if="item.prop!=='price'"
            v-for="(item,i) in skuListLabel"
            :key="i"
            :prop="item.prop"
            :label="item.label"
            width="180"
          >
          </el-table-column>
          <el-table-column
            v-else
            prop="price"
            label="价格(元)"
            style="width: 100px"
          >
            <template slot-scope="scope">
              <el-input
                v-model="priceList[scope.$index]"
                placeholder=""
                style="width: 100px"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item
        label="服务封面："
        prop="mainPicId"
        :rules="[
          { required: true, message: '请上传封面', trigger: 'change' }
        ]"
      >
        <single-upload v-model="content.mainPicId"></single-upload>
      </el-form-item>
      <el-form-item label="时间段1：">
        <el-input
          v-model="content.time1"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="时间段2：">
        <el-input
          v-model="content.time2"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="副标题："
        prop="specDesc"
        :rules="[
          { required: true, message: '请填写副标题', trigger: 'change' }
        ]"
      >
        <el-input
          v-model="content.specDesc"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="服务详情：">
        <div
          ref="editor"
          class="editor-wrapper"
        ></div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit('contentFrom')"
        >提交</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import SingleUpload from '@/components/Upload/singleUpload'
import WEditor from 'wangeditor'
import { prptypackageList } from '@/api/goodsMs'
import {
  prodSpecsave,
  getProdSpecById,
  getProdSpecSkuListShow
} from '@/api/servMs'
import { serverspecList } from '@/api/deptInst'

const defaultContent = {
  specName: '',
  serType: [],
  packageName: '',
  mainPicId: '',
  specDesc: '',
  time1: '',
  time2: ''
}
const listToTree = (list, tree, parentId) => {
  list.forEach((item) => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        value: item.id,
        label: item.serverSpecName,
        children: []
      }
      if (!child.component) child.entry = ''
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}

export default {
  name: 'MenuDetail',
  components: { SingleUpload },
  data () {
    return {
      showPrice: false,

      content: Object.assign({}, defaultContent),
      serTypeList: [],
      prptyPackageId: '',
      skuTableData: [],
      skuListLabel: [],
      saveSkuTableData: [],
      priceList: [],
      isEdit: false
    }
  },
  mounted () {
    this.isEdit = this.$route.query.isEdit
    if (!this.isEdit) {
      this.initEditor('')
    }
    this.getList()
  },
  methods: {
    getDetail () {
      getProdSpecById({ prodSpecId: this.$route.query.id }).then((response) => {
        const {
          specName,
          serverSpecId,
          mainPicId,
          specDesc,
          pmProdSpecDetail: { prodSpecDetail },
          prptyPackageId,
          prprtyPackage: { name },
          skuTableData,
          skuListLabel
        } = response.data

        const rules0serType = []
        this.serTypeList.map((items) => {
          if (items.id === serverSpecId) {
            rules0serType.push(serverSpecId)
            return false
          }
          if (items.children && items.children.length > 0) {
            items.children.map((item) => {
              if (item.id === serverSpecId) {
                rules0serType.push(items.id, serverSpecId)
                return false
              }
            })
          }
        })

        const tempValue = eval(
          '(' + response.data.prodSpecStockTempList[0].tempValue + ')'
        )
        this.content = Object.assign(
          {},
          {
            specName,
            packageName: name,
            mainPicId,
            specDesc,
            serType: rules0serType,
            // time1: tempValue[0],
            // time2: tempValue[1],
            time1: (tempValue[0] && tempValue[0].time) || '',
            time2: (tempValue[1] && tempValue[1].time) || ''
          }
        )
        this.$set(this.content, 'serType', rules0serType)

        this.prptyPackageId = prptyPackageId
        this.skuTableData = skuTableData
        this.skuListLabel = skuListLabel
        skuTableData.map((item) => {
          this.priceList.push(item.price)
        })
        this.showPrice = true
        this.initEditor(prodSpecDetail)
      })
    },
    serTypeChange () {
      this.content.packageName = ''
    },
    getList () {
      const data = {
        parentId: '',
        isNeedPic: true,
        serverSpecName: '',
        serverSpecLevel: ''
      }
      serverspecList(data).then((response) => {
        listToTree(response.data, this.serTypeList, 0)
        if (this.isEdit) {
          this.getDetail()
        }
      })
    },
    packageQuerySearchAsync (queryString, cb) {
      const params = {
        pageNum: 1,
        pageSize: 100,
        packageName: queryString
      }
      prptypackageList(params).then((res) => {
        const results = res.data.list.map((item) => {
          item.value = item.name
          return item
        })
        cb(results)
      })
    },
    packageSelect (e) {
      this.prptyPackageId = e.id
    },

    priceChange () {
      this.showPrice = true
      const data = {
        prodSpecId: '',
        packageId: this.prptyPackageId
      }
      getProdSpecSkuListShow(data).then((response) => {
        this.skuTableData = response.data.skuTableData
        this.skuListLabel = response.data.skuListLabel
        this.priceList = []
      })
    },
    initEditor (content) {
      this.editor = new WEditor(this.$refs.editor)
      // this.editor.customConfig.debug = true
      this.editor.customConfig.uploadImgServer = '/zdmanage/upload'
      this.editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
      // this.editor.customConfig.uploadImgParams = {
      //   busiType: 'rich'
      // }
      this.editor.customConfig.customAlert = function (info) {
        // message.error(info)
      }
      this.editor.customConfig.uploadFileName = 'file'
      this.editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result) {
          if (!result.data) {
            // message.error(result.resultMessage)
          } else {
            insertImg(result.data)
          }
        }
      }
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        // 'link', // 插入链接
        // 'list', // 列表
        'justify', // 对齐方式
        // 'quote', // 引用
        // 'emoticon', // 表情
        'image', // 插入图片
        // 'table', // 表格
        // 'video', // 插入视频
        // 'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ]
      // this.editor.customConfig.onchange = (html) => {
      //   this.editorContent = html
      //   this.$emit('change', this.editorContent)
      // }
      this.editor.create()
      this.editor.txt.html(content)
    },
    onSubmit (formName) {
      const {
        specName,
        serType,
        mainPicId,
        specDesc,
        time1,
        time2
      } = this.content

      const skuTableData = this.skuTableData.map((item, index) => {
        item.price = this.priceList[index]
        return item
      })

      if (skuTableData.length === 0) {
        this.$message({
          message: '请填写价格配置',
          type: 'error',
          duration: 1000
        })
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = {
              specName,
              serverSpecId: serType[serType.length - 1],
              prptyPackageId: this.prptyPackageId,
              skuTableData,
              mainPicId,
              specDesc,
              pmProdSpecDetail: {
                prodSpecDetail: this.editor.txt.html()
              },
              prodSpecStockTempList: [
                {
                  tempType: 12,
                  tempValue: JSON.stringify([{ time: time1 }, { time: time2 }])
                }
              ]
            }

            this.serTypeList.map((item) => {
              if (item.id === params.serverSpecId) {
                params.serverSpecName = item.serverSpecName
              }
              if (item.children && item.children.length > 0) {
                item.children.map((item) => {
                  if (item.id === params.serverSpecId) {
                    params.serverSpecName = item.serverSpecName
                  }
                })
              }
            })

            if (this.isEdit) {
              params.id = this.$route.query.id
            }
            console.log(params)
            prodSpecsave(params).then((response) => {
              this.$refs[formName].resetFields()
              this.resetForm(formName)
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1000
              })
              this.$router.back()
            })
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.content = Object.assign({}, defaultContent)
    },
    back () {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.form-container {
  position: relative;
  z-index: 0;
  width: 800px;
}
</style>
